package com.livepan.file.controller;

import com.alibaba.druid.util.StringUtils;
import com.livepan.file.FileApplication;
import com.livepan.server.enums.FileUseEnum;
import com.livepan.server.error.BusinessException;
import com.livepan.server.error.EmBusinessError;
import com.livepan.server.response.CommonReturnType;
import com.livepan.server.service.FileService;
import com.livepan.server.service.model.FileModel;
import com.livepan.server.service.model.UserModel;
import com.livepan.server.utils.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Date;
import java.util.Locale;

@RestController
@RequestMapping(value = "/admin")
public class UploadController {

    private static final Logger LOG = LoggerFactory.getLogger(FileApplication.class);

    public static final String BUSINESS_NAME = "文件上传";

    @Value("${file.path}")
    private String FILE_PATH;
    @Value("${file.domain}")
    private String FILE_DOMAIN;

    @Autowired
    private FileService fileService;

    @RequestMapping(value = "/upload")
    @ResponseBody
    public CommonReturnType upload(@RequestParam MultipartFile file,
                                   @RequestParam("use") String use)
            throws IOException, BusinessException {
        LOG.info("文件上传开始:{}", file);
        LOG.info(file.getOriginalFilename());
        LOG.info(String.valueOf(file.getSize()));

        //保存文件到本地
        FileUseEnum useEnum = FileUseEnum.getByCode(use);
        String fileName = file.getOriginalFilename();
        String suffix = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
        String key = UUIDUtil.getShortUUID();

        assert useEnum != null;
        String dir = useEnum.name().toLowerCase(Locale.ROOT);
        FileUtil.checkDirPath(FILE_PATH + dir);

        String path = dir + "/" + key + "." + suffix;
        String fullPath = FILE_PATH + path;
        File dest = new File(fullPath);
        file.transferTo(dest);
        LOG.info(dest.getAbsolutePath());
        String urlPath = FILE_DOMAIN + dir + "/" + key + "." + suffix;

        FileModel fileModel = new FileModel();
        fileModel.setName(file.getOriginalFilename());
        fileModel.setPath(path);
        fileModel.setSize(Math.toIntExact(file.getSize()));
        fileModel.setSuffix(suffix);
        fileModel.setPurpose(useEnum.getCode());
        fileModel.setUpdatedAt(new Date(dest.lastModified()));
        fileModel.setCreatedAt(new Date(dest.lastModified()));
        fileService.save(fileModel);


        return CommonReturnType.create(urlPath);
    }
}
